package com.gitee.wsl.android.ext.device

import android.content.Context
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.VibrationEffect
import android.os.VibrationEffect.Composition.PRIMITIVE_SLOW_RISE
import android.os.Vibrator
import android.os.VibratorManager
import android.provider.Settings
import com.gitee.wsl.android.ext.ApplicationInit.application
import com.gitee.wsl.android.ext.device.VibrateExt.TICK

val globalVibratorManager:Vibrator by lazy { application.vibrator }

val Context.vibrator: Vibrator get() {
    return if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
        val manager =getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
        manager.defaultVibrator
    } else {
          getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
    }
}

val Context.areSystemHapticsTurnedOn:Boolean get() = Settings.System.getInt(contentResolver, Settings.System.HAPTIC_FEEDBACK_ENABLED, 0)!=0

object VibrateExt {
    const val TICK: Long = 13
    const val CLICK: Long = 20
    const val HEAVY: Long = 50
}

val Vibrator.enabled:Boolean get()=hasVibrator()

fun Vibrator.vibrate( duration:Long) {
    if (!enabled) {
        return
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        vibrate(VibrationEffect.createOneShot(duration, VibrationEffect.DEFAULT_AMPLITUDE))
    } else {
        vibrate(duration)
    }
}

fun Vibrator.vibrate( effectId:Int) {
    if (!enabled) {
        return
    }
    if (enabled && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        vibrate(VibrationEffect.createPredefined(effectId));
    }
}

fun Vibrator.tick(){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        vibrate(VibrationEffect.EFFECT_TICK)
    } else {
        vibrate(TICK)
    }
}

fun Vibrator.click(){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        vibrate(VibrationEffect.EFFECT_CLICK)
    } else {
        vibrate(VibrateExt.CLICK)
    }
}

fun Vibrator.doubleClick(){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        vibrate(VibrationEffect.EFFECT_DOUBLE_CLICK)
    } else {
        vibrate(VibrateExt.CLICK)
        Handler(Looper.getMainLooper()).postDelayed({ vibrate(VibrateExt.CLICK) }, 100)
    }
}

fun Vibrator.heavyClick() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        vibrate(VibrationEffect.EFFECT_HEAVY_CLICK)
    } else {
        vibrate(VibrateExt.HEAVY)
    }
}

fun Vibrator.explode() {
    if (enabled && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        vibrate(
            VibrationEffect.startComposition().addPrimitive(PRIMITIVE_SLOW_RISE).compose()
        )
    } else {
        heavyClick()
    }
}

